package com.ruoyi.web.controller.util;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.info.domain.VehiclesYj;
import com.ruoyi.info.domain.VinfoCountOrder;
import com.ruoyi.info.domain.vo.CarLocationVo;
import com.ruoyi.info.service.IVehiclesYjService;
import com.ruoyi.info.service.IVinfoCarService;
import com.ruoyi.info.service.IVinfoCountOrderService;
import com.ruoyi.wx.domain.VehiclesLog;
import com.ruoyi.wx.service.IVehiclesLogService;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class CarUtil {
    @Resource
    private IVehiclesLogService vehiclesLogService;

    @Resource
    private IVinfoCarService infoCarService;

    @Resource
    private IVinfoCountOrderService vinfoCountOrderService;

    @Resource
    private IVehiclesYjService vehiclesYjService;

    public static CarUtil carUtil;

    @PostConstruct
    public void init(){
        carUtil = this;
        carUtil.vehiclesLogService = this.vehiclesLogService;
        carUtil.infoCarService = this.infoCarService;
        carUtil.vinfoCountOrderService = this.vinfoCountOrderService;
        carUtil.vehiclesYjService = this.vehiclesYjService;
    }

    public Map<String,Object> handleLocations(List<CarLocationVo> carLocationVoList){
        //设备id列表
        List<String> deviceNoList = new ArrayList<>();
        //将设备id添加到设备id列表
        for (CarLocationVo carLocationVo : carLocationVoList) {
            deviceNoList.add(carLocationVo.getDeviceNo());
        }

        //结果集合
        Map<String,Object> resultMap = new HashMap<>();

        //在线数量
        int onlineNum = 0;

        //离线数量
        int offlineNum = 0;

        //获取请求结果
        AjaxResult result = RequestUtil.getLocations(deviceNoList);

        if (result.get("code").toString().equals("200")) {
            String data = result.get("data").toString();
            //将data转为List<VehicleLog>类型并存放到vehicleLogs中
            List<VehiclesLog> vehiclesLogs = JSON.parseObject(data, new TypeReference<ArrayList<VehiclesLog>>() {});

            for (CarLocationVo locationVo : carLocationVoList) {
                //设置展示图片
                if (locationVo.getImage() != null) {
                    locationVo.setImage(locationVo.getImage().split(",")[0]);
                }
                for (VehiclesLog vehiclesLog : vehiclesLogs) {
                    if (vehiclesLog.getDeviceNo().equals(locationVo.getDeviceNo())) {

                        locationVo.setSpeed(vehiclesLog.getSpeed());

                        //经纬度转换
                        Double x = vehiclesLog.getX();
                        Double y = vehiclesLog.getY();
//                        mapUtil.transGpslocToBaiduloc(x, y);
//                        locationVo.setLat(mapUtil.getLat());
//                        locationVo.setLot(mapUtil.getLot());
//                        double[] loc = MapUtil.gcj2bd(y,x);
//                        locationVo.setLot(loc[1]);
//                        locationVo.setLat(loc[0]);

                        double[] loc = CoordinateTransformUtil.gcj02tobd09(x,y);
                        locationVo.setLot(loc[0]);
                        locationVo.setLat(loc[1]);

                        //获取重量
                        String eventDesc = vehiclesLog.getEventDesc();
                        String weightStr;
                        if (eventDesc == null || !eventDesc.contains("AD0")) {
                            weightStr = "0";
                        } else {
                            //AD0的位置
                            int index = eventDesc.indexOf("AD0");
                            //AD1的位置
                            int index1 = eventDesc.indexOf("AD1");

                            weightStr = eventDesc.substring(index + 4, index1 - 1);
                        }
                        double weight = Double.parseDouble(weightStr);
                        double iniWeight = locationVo.getIniweight();
                        double realWeight = weight - iniWeight;
                        if (realWeight > 0){
                            locationVo.setWeightStatus("载货");
                            locationVo.setWeight("约" +weight/1000 + "吨");
                        }else {
                            locationVo.setWeightStatus("空载");
                            locationVo.setWeight("无");
                        }

                        //设置在线状态
                        String realTimeStatus = vehiclesLog.getRealTimeStatus();
                        String isOnline = "";
                        String status = "";
                        String statusDurationStr;
                        switch (realTimeStatus) {
                            case "0":
                                isOnline = "0";
                                status = "未上线";
                                offlineNum += 1;
                                break;
                            case "1":
                                isOnline = "0";
                                status = "离线";
                                offlineNum += 1;
                                break;
                            case "2":
                                isOnline = "1";
                                status = "停车";
                                onlineNum += 1;
                                break;
                            case "3":
                                isOnline = "1";
                                status = "行驶";
                                onlineNum += 1;
                                break;
                            case "4":
                                isOnline = "1";
                                status = "停留";
                                onlineNum += 1;
                                break;
                            case "5":
                                isOnline = "0";
                                status = "维修";
                                offlineNum += 1;
                                break;
                            case "6":
                                isOnline = "0";
                                status = "报废";
                                offlineNum += 1;
                                break;
                        }
                        int statusDuration = Integer.parseInt(vehiclesLog.getStatusDuration());
                        if (statusDuration > 0){
                            statusDurationStr = DateUtil.formateDate(statusDuration);
                            locationVo.setStatusDuration(statusDurationStr);
                        }else {
                            locationVo.setStatusDuration("");
                        }
                        locationVo.setIsOnline(isOnline);
                        locationVo.setStatus(status);
                        break;
                    }
                }
            }
        }
        resultMap.put("carLocationVoList",carLocationVoList);
        resultMap.put("onlineNum",onlineNum);
        resultMap.put("offlineNum",offlineNum);
        return resultMap;
    }

    public static AjaxResult statistic(String url, String body){
        String endTime = JacksonUtil.parseString(body,"endTime");
        String startTime = JacksonUtil.parseString(body,"startTime");
        String pageNumber = JacksonUtil.parseString(body,"pageNumber");
        String pageSize = JacksonUtil.parseString(body,"pageSize");
        List<String> onlineIdList = new ArrayList<>();
        List<String> carNoList = JacksonUtil.parseStringList(body,"carNoList");
        List<CarLocationVo> carLocationVoList = carUtil.infoCarService.selectCarLocationsByCarNos(carNoList);
        carLocationVoList.forEach(carLocationVo -> {
            carLocationVo.setCountWeight(carUtil.vehiclesLogService.selectCountWeight(carLocationVo.getCarNo(),new Date(Long.parseLong(startTime)),new Date(Long.parseLong(endTime))));
        });
        for (CarLocationVo carLocationVo : carLocationVoList){
            onlineIdList.add(carLocationVo.getOnlineId());
        }
        Map<String,Object> params = new HashMap<>();
        params.put("carIdList",onlineIdList);
        params.put("endTime",endTime);
        params.put("startTime",startTime);
        params.put("pageNumber",pageNumber);
        params.put("pageSize",pageSize);
        AjaxResult ajaxResult = RequestUtil.post(url,params);
        System.out.println("ajaxResult = " + ajaxResult);
        if (ajaxResult.get("code").toString().equals("200")){
            String dataMapStr = ajaxResult.get("data").toString();
            Map<String,Object> dataMap = JSON.parseObject(dataMapStr,new TypeReference<Map<String,Object>>(){});
            String dataListStr = dataMap.get("dataList").toString();
            List<Map<String,Object>> dataList = JSON.parseObject(dataListStr, new TypeReference<ArrayList<Map<String,Object>>>(){});
            for (Map<String,Object> map : dataList){
                for (CarLocationVo carLocationVo : carLocationVoList) {
                    if (map.get("carId").toString().equals(carLocationVo.getOnlineId())){
                        map.put("compName",carLocationVo.getCompName());
                        map.put("driverName",carLocationVo.getDriverName());
                        map.put("driverPhone",carLocationVo.getDriverPhone());
                        map.put("carNo",carLocationVo.getCarNo());
                        map.put("countWeight",carLocationVo.getCountWeight());
                    }
                }
            }
            ajaxResult.put("dataList",dataList);
        }
        return ajaxResult;
    }

    public static void writingLog(long finalBegin,int finalPageSize){
        //获取车辆信息
        List<CarLocationVo> carLocationVoList = carUtil.infoCarService.selectAllCarLocationsByPage(finalBegin, finalPageSize);
        //设备id列表
        List<String> deviceNoList = new ArrayList<>();
        //将设备id添加到设备列表
        for (CarLocationVo carLocationVo : carLocationVoList) {
            deviceNoList.add(carLocationVo.getDeviceNo());
        }
        //获取设备信息
        String url = "https://api.ly-gps.com/lygps-api/v2/locate/getDeviceLocate";
        Map<String, Object> params = new HashMap<>();
        params.put("deviceNoList", deviceNoList);
        //获取设备信息
        AjaxResult res = RequestUtil.post(url, params);

        assert res != null;
        if (res.get("code").toString().equals("200")) {
            //取出接口返回的数据字符串并转为List<Map<>>集合
            String data = res.get("data").toString();
            List<VehiclesLog> vehiclesLogList = JSON.parseObject(data, new TypeReference<ArrayList<VehiclesLog>>() {});

            //将本地信息与接口信息配对
            for (CarLocationVo carLocationVo : carLocationVoList) {
                boolean isMatch = false;
                for (VehiclesLog vehiclesLog : vehiclesLogList) {
                    if (vehiclesLog.getDeviceNo().equals(carLocationVo.getDeviceNo())) {
                        Object extendObjext = vehiclesLog.getExtend();
                        if (!Objects.isNull(extendObjext)){
                            String extendString = extendObjext.toString();
                            if(!StringUtils.isEmpty(extendString)){
                                if (extendString.contains("weight")) {
                                    JSONObject jsonObject = JSONObject.parseObject(extendString);
                                    String[] ADArray = jsonObject.getString("weight").split(",");
                                    String AD0 = ADArray[0];
                                    String AD1 = ADArray[1];
                                    vehiclesLog.setCarNo(carLocationVo.getCarNo());     //设置车牌号
                                    vehiclesLog.setCarId(carLocationVo.getCarId());     //设置车辆id
                                    vehiclesLog.setPersonName(carLocationVo.getDriverName());   //设置驾驶员姓名
                                    if (!vehiclesLog.getEventDesc().contains("AD0")) {
                                        vehiclesLog.setEventDesc(vehiclesLog.getEventDesc() + "AD0:" + AD0 + ",AD1:" + AD1);
                                    }
                                    String eventDesc = vehiclesLog.getEventDesc();
                                    System.out.println(eventDesc);
                                }
                            }
                        }

                        String eventDesc = vehiclesLog.getEventDesc();
                        if (eventDesc.contains("AD0:0")){
                            VehiclesYj vehiclesYj = new VehiclesYj();
                            vehiclesYj.setCarNo(vehiclesLog.getCarNo());
                            vehiclesYj.setStatus("0");
                            vehiclesYj.setEventDesc(eventDesc);
                            vehiclesYj.setRemark("无重量返回");
                            if (carUtil.vehiclesYjService.selectVehiclesYjList(vehiclesYj) == null ||  carUtil.vehiclesYjService.selectVehiclesYjList(vehiclesYj).size() <= 0) {
                                vehiclesYj.setCrateTime(new Date());
                                carUtil.vehiclesYjService.insertVehiclesYj(vehiclesYj);
                            }
                        }else if(eventDesc.contains("断电报警") || eventDesc.contains("GPS无信号")){
                            VehiclesYj vehiclesYj = new VehiclesYj();
                            vehiclesYj.setCarNo(vehiclesLog.getCarNo());
                            vehiclesYj.setStatus("0");
                            vehiclesYj.setEventDesc(eventDesc);
                            if (carUtil.vehiclesYjService.selectVehiclesYjList(vehiclesYj) == null ||  carUtil.vehiclesYjService.selectVehiclesYjList(vehiclesYj).size() <= 0) {
                                vehiclesYj.setCrateTime(new Date());
                                carUtil.vehiclesYjService.insertVehiclesYj(vehiclesYj);
                            }
                        }

                        String[] alarmList = vehiclesLog.getAlarmList();
                        StringBuilder alarmLists = new StringBuilder();
                        for (int k = 0; k < alarmList.length; k++) {
                            if (k > 0) {
                                alarmLists.append(",");
                            }
                            alarmLists.append(alarmList[k]);
                        }
                        vehiclesLog.setAlarmLists(alarmLists.toString());
                        carUtil.vehiclesLogService.insertVehiclesLog(vehiclesLog);
                        isMatch = true;
                        break;
                    }
                }
                if (!isMatch) {
                    VehiclesLog vehiclesLog = new VehiclesLog();
                    vehiclesLog.setCarNo(carLocationVo.getCarNo());     //设置车牌号
                    vehiclesLog.setCarId(carLocationVo.getCarId());     //设置车辆id
                    carUtil.vehiclesLogService.insertVehiclesLog(vehiclesLog);
                }
            }
        }
    }

    public static AjaxResult statistic(String body){
        AjaxResult ajaxResult = AjaxResult.success();
        Date endTime = new Date(Objects.requireNonNull(JacksonUtil.parseBigDecimal(body, "endTime")).longValue());
        System.out.println("endTime = " + endTime);
        Date startTime = new Date(Objects.requireNonNull(JacksonUtil.parseBigDecimal(body, "startTime")).longValue());
        Integer page = JacksonUtil.parseInteger(body,"pageNumber");
        Integer limit = JacksonUtil.parseInteger(body,"pageSize");
        List<String> carNoList = JacksonUtil.parseStringList(body,"carNoList");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        List<VinfoCountOrder> dataList = carUtil.vinfoCountOrderService.selectCountByDate(startTime,endTime,page,limit,carNoList);

        Long total = carUtil.vinfoCountOrderService.selectTotalByDate(startTime,endTime,carNoList);
        dataList.forEach(vinfoCountOrder -> {
            vinfoCountOrder.setStartTime(simpleDateFormat.format(startTime));
        });
        Map<String,Object> resultMap = new HashMap<>();

        resultMap.put("dataList",dataList);
        resultMap.put("total",total);
        resultMap.put("pageNumber",page);
        resultMap.put("pageSize",limit);

        ajaxResult.put("data",resultMap);
        ajaxResult.put("dataList",dataList);
        return ajaxResult;
    }

    public List<VinfoCountOrder> getCount(Long start,Long end,  Integer page, Integer limit,String[] carNos){

//        JSONObject jsonObject = JSON.parseObject(body);
//
//        Date endTime = new Date(jsonObject.getLong("endTime"));
//        Date startTime = new Date(jsonObject.getLong("startTime"));
//        Integer page = jsonObject.getInteger("pageNumber");
//        Integer limit = jsonObject.getInteger("pageSize");
//        List<String> carNoList = jsonObject.getObject("carNoList",new TypeReference<List<VinfoCountOrder>>(){});
        Date startTime = new Date(start);
        Date endTime = new Date(end);
        List<String> carNoList = null;
        if (carNos != null) {
            carNoList = Arrays.asList(carNos);
        }

        return carUtil.vinfoCountOrderService.selectCountByDate(startTime,endTime,page,limit,carNoList);
    }
}
